package file

import (
	"controllers"
	"github.com/astaxie/beego"
	"models"
	"encoding/json"
	"library/components"
	"os"
	"io"
	"github.com/astaxie/beego/orm"
	"strconv"
)


// ConsoleScriptController operations for ConsoleScript
type FileDistributeController struct {
	controllers.BaseRouter
}


func (c *FileDistributeController) UploadFile() {
	//异步执行
	go func(){
		//获取上传文件
		_, err := uploadFiles(c)
		if err != nil {
			c.SetJson(1, nil, "文件获取失败"+err.Error())
			return
		}
	}()

	c.SetJson(200, nil, "上传文件")
	return
}

func (c *FileDistributeController) DeleteUploadFile() {
	//获取讲删除的文件名
	delFileName := c.GetString("filename")
	beego.Info(delFileName)
	//清除上传文件
	err := components.CleanUpLocal(beego.AppConfig.String("file_upload") + delFileName)
	if err != nil {
		c.SetJson( 1,nil,"文件删除失败"+err.Error())
		return
	}
	c.SetJson(200, nil, "删除成功")
	return
}

func (c *FileDistributeController) FileDistribute () {
	//新建任务入库
	if c.User == nil  {
		c.SetJson(2, nil, "not login")
		return
	}
	beego.Info(string(c.Ctx.Input.RequestBody))
	var task models.GjFileTask
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &task)
	if err != nil {
		c.SetJson(1, nil, "数据获取异常"+err.Error())
	}
	_,err = models.AddGjFileTask(&task)
	if err != nil {
		c.SetJson(1, nil, "脚本执行任务录入失败")
	}

	//file 指的是部署服务器文件所在目录
	//如果是网页端操作本地文件上传需上传至部署机器，分发完成后清空文件

	//异步执行
	go func(){
		s := components.FileBaseComponents{}
		s.SetFileTask(&task)

		//获取上传文件
		fileNames:= s.GetFileName(task.Files)
		beego.Info(fileNames)

		for _,file := range fileNames {
			if task.Type == 1 {   	   //type == 1 use p2p
				_,err = s.CopyFilesByP2p(file+"transfer",beego.AppConfig.String("file_upload") + file,task.FileTargetPath+"/"+file,components.GetHosts(task.TargetIpHosts))
				if err != nil {
					continue
				}
				components.CleanUpLocal(beego.AppConfig.String("file_upload") + file)
			}else {
				_,err :=s.CopyFilesBySftp(beego.AppConfig.String("file_upload") + file,task.FileTargetPath + "/"+file,components.GetHosts(task.TargetIpHosts))
				if err != nil {
					continue
				}
				components.CleanUpLocal(beego.AppConfig.String("file_upload") + file)
			}
		}

		InsertOption(0,task.Id,task.Files,c.User.UserName)
	}()


	c.SetJson(200, task.Id, "开始执行脚本")
	return
}



func uploadFiles(c *FileDistributeController) (desFiles []string, err error) {
	files, err := c.GetFiles("file")
	if err != nil {
		return nil , err
	}
	for i, _ := range files {
		file, err := files[i].Open()
		defer file.Close()
		if err != nil {
			return nil , err
		}
		//create destination file making sure the path is writeable.
		dst, err := os.Create(beego.AppConfig.String("file_upload")  + files[i].Filename)
		defer dst.Close()
		if err != nil {
			return nil , err
		}
		//copy the uploaded file to the destination file
		if _, err := io.Copy(dst, file); err != nil {
			return nil , err
		}

		desFiles = append (desFiles,beego.AppConfig.String("file_upload")  + files[i].Filename)
	}
	return desFiles,nil
}

func InsertOption(types int,task_id int,content string,operator string) error {
	o := orm.NewOrm()
	sqlString := "insert into gj_history(type,task_id,content,operator) values(" + strconv.Itoa(types) + "," + strconv.Itoa(task_id) + ",'" + "distribute " + content + "','" + operator + "')"
	beego.Info(sqlString)
	_,err := o.Raw(sqlString).Exec()
	if err !=nil {
		return err
	}
	return nil
}